const sha1 = require("crypto-js/sha1");
const d = {}
const charList = [" ", "#", "?", "/", "(", ")", ":", "[", "]", "@", "!", "$", "&", "'", '"', "*", "+", ",", ";"]
d.hashLink = (link) => {
  return sha1(link).toString();
};

d.escapeUrl = (url) => {
  let escapeUrl = url;
  for (const charToReplace of charList){
    escapeUrl = escapeUrl.replaceAll(charToReplace, "_");
  }
  while (escapeUrl.indexOf("__") !== -1) {
    escapeUrl = escapeUrl.replaceAll("__", "_");
  }
  return d.stripLeft(escapeUrl, "_"); // strip the leading "_" because it would concact with hash with "_"
};

d.stripLeft = (s, charVal) => {
  if (s && s.length) {
    let pos = 0;
    for (let i = 0; i < s.length; i++) {
      if (s[i] != charVal)
        break;
      pos++;
    }
    s = s.substring(pos);
  }
  return s;
}

d.stripRight = (s, charVal) => {
  if (s && s.length) {
    let pos = s.length;
    for (let i = s.length - 1; i >= 0; i--) {
      if (s[i] != charVal)
        break;
      pos--;
    }
    s = s.substring(0, pos);
  }
  return s;
}
module.exports = d;
